from django.shortcuts import render
from django_filters.rest_framework.backends import DjangoFilterBackend
from drf_haystack.viewsets import HaystackViewSet
from rest_framework.filters import OrderingFilter
from rest_framework.generics import ListAPIView, GenericAPIView
from rest_framework.response import Response

from goods.models import SKU, GoodsCategory

from goods.serializers import SKUSerializer, ChannelSerializer, CategorySerializer, SKUIndexSerializer


class CategoryView(GenericAPIView):
    """
    商品列表页面包屑导航
    """
    queryset = GoodsCategory.objects.all()

    # GET /categories/1/
    def get(self, request, pk=None):
        ret = {
            'cat1': '',
            'cat2': '',
            'cat3': '',
        }
        category = self.get_object()
        if category.parent is None:
            # 当前类别为一级类别
            # 通过 频道 查询 类别：  category.goodschannel_set.all()[0]
            ret['cat1'] = ChannelSerializer(category.goodschannel_set.all()[0]).data
        elif category.goodscategory_set.count() == 0:
            # 当前类别为三级
            ret['cat3'] = CategorySerializer(category).data
            cat2 = category.parent
            ret['cat2'] = CategorySerializer(cat2).data
            ret['cat1'] = ChannelSerializer(
            	cat2.parent.goodschannel_set.all()[0]).data
        else:
            # 当前类别为二级
            ret['cat2'] = CategorySerializer(category).data
            ret['cat1'] = ChannelSerializer(
            	category.parent.goodschannel_set.all()[0]).data
        return Response(ret)




# 实现方式一  查询商品列表数据(广告图)
class SKUListView(ListAPIView):
    """
    sku列表数据
    """
    print('123')
    serializer_class = SKUSerializer # 关联的序列化器
    filter_backends = (OrderingFilter,)  # 排序器后台
    ordering_fields = ('create_time', 'price', 'sales') #指定根据哪些字段进行排序

    def get_queryset(self):
        category_id = self.kwargs['category_id']	# 获取url路径中的参数

        return SKU.objects.filter(category_id=category_id, is_launched=True)  # 过滤上架商品


# 实现方式二　查询商品列表数据
class SKUListView2(ListAPIView):
    """
    sku列表数据
    """
    serializer_class = SKUSerializer # 关联的序列化器
    queryset = SKU.objects.filter(is_launched=True) # 查询集　上架的商品

    # 排序和过滤的后台　参数１实现过滤的　参数２实现排序的
    filter_backends = (DjangoFilterBackend,OrderingFilter)
    # 指定可以根据哪些字段进行列表数据的过滤 (内只有一个参数要加,和空一格)
    # 根据查询集再过滤字段商品信息
    filter_fields = ('category_id', ) # 指定的是模型类里面的字段
    ordering_fields = ('create_time', 'price', 'sales') # 指定排序的字段


# 商品搜索
class SKUSearchViewSet(HaystackViewSet):
    """
    SKU搜索
    HaystackViewSet： 查一条，查多条
    """
    print('拿到')
    index_models = [SKU] # 关联的模型类
    serializer_class = SKUIndexSerializer # 关联的序列化器


